import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebPage2 extends StatefulWidget {
  const WebPage2({super.key});

  @override
  State<WebPage2> createState() => _WebPage2State();
}

class _WebPage2State extends State<WebPage2> {
  // 1
  late WebViewController controller;
  String message = "init";

  int paramId = 0;
  double height = 0;

  @override
  void initState() {
    super.initState();
    _initWebView();
    controller.loadFlutterAsset("assets/html/index.html");
  }

  _logFlutter(String msg) {
    print(msg);
    setState(() {
      message = msg;
    });
  }

  _initWebView() async {
    // 2
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      // ..loadRequest(Uri.parse("https://www.baidu.com"))
      // ..loadFlutterAsset("assets/html/index.html")
      // ..loadHtmlString('<a href="/frontend">打开前段页面</a>')
      // ...
      ..addJavaScriptChannel(
        "flutterObj",
        onMessageReceived: (JavaScriptMessage message) {
          _logFlutter("flutterObj, msg: ${message.message}");
          setState(() {
            this.message = message.message;
            height += 20;
          });
        },
      );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ElevatedButton(
          onPressed: () => _runJsOnly(),
          child: const Text("runJavaScript"),
        ),
        ElevatedButton(
          onPressed: () => _runJsWithResult(),
          child: const Text("runJavaScriptReturningResult"),
        ),
        ElevatedButton(
          onPressed: () => _runJsWithParam(),
          child: const Text("runJavaScriptWithParam"),
        ),
        Text(message),
        SizedBox(height: 200 + height),
        Expanded(
          child: WebViewWidget(controller: controller),
        ),
      ],
    );
  }

  _runJsOnly() {
    _logFlutter('_runJsOnly');
    controller.runJavaScript('runJsOnly()');
    setState(() {
      if (height < 100) {
        height += 10;
      } else {
        height = 10;
      }
    });
  }

  _runJsWithResult() async {
    String jsStr = "runJsWithResult()";
    var result = await controller.runJavaScriptReturningResult(jsStr);
    _logFlutter("_runJsWithResult js=$jsStr, res=$result");
  }

  _runJsWithParam() async {
    var param = "FlutterParamString${++paramId}";
    String jsStr = "runJsWithParam('$param')";
    var result = await controller.runJavaScriptReturningResult(jsStr);
    _logFlutter("js=$jsStr, res=$result");
  }
}
